﻿
// Binding "pageinit" ensures that code is called
// each time the virtual page is displayed

$("#detail").live("pageinit", function (event) {
    updateDetail(); // When the page is displayed, fetch content and update the UI
    return false;
});

$("#edit").live("pageinit", function (event) {

    // Bind to the form submit and handle with AJAX
    // JQM can do this automatically, but we are
    // doing it manually here in order to have a 
    // smoother UX where the page content refreshes
    // after the edit dialog is submitted.
    $("#edit form").submit(function () {

        var url = $(this).attr("action");
        var jsonData = "{ 'description' : '" + $('#description').val() + "'}";
        $.ajax({
            type: "POST",
            url: url,
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            data: jsonData,
            processData: false
        })
        .fail(function (xhr) {
            displayMessage(xhr.responseText);
        })
        .done(function () {
            $(".ui-dialog").dialog("close");
            updateDetail();
        });

        return false;
    });

});

function updateDetail() {
    var url = $("#detail").attr("rel");
    $.ajax({
        type: "POST",
        url: url
    })
    .fail(function (xhr) {
        displayMessage(xhr.responseText);
    })
    .done(function (product) {
        ko.applyBindings(product); // Use knockoutJs to bind model to view    
    });
}